import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PAGINATION_OPTIONS, TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FIXED_COLUMN_WIDTH} from '../constants';
import {injectIntl} from './intl';
import {conventEnumValueToString} from '../utils';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {dutyUnitStatus, isYorN} from '../Enum';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {stopData, startData} from './api';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickStartBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        startData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickStopBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        stopData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    render() {
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'brandCode' && this.props.sortedOrder
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '责任单位编号'
                }),
                dataIndex: 'code',
                width: '100px',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.name',
                    defaultMessage: '责任单位名称'
                }),
                dataIndex: 'name',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'name' && this.props.sortedOrder,
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.enterpriseCode',
                    defaultMessage: '公司代码'
                }),
                dataIndex: 'enterpriseCode',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'enterpriseCode' && this.props.sortedOrder,
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
                render: text => conventEnumValueToString(dutyUnitStatus, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.isSecondClaim',
                    defaultMessage: '是否生成二次索赔'
                }),
                dataIndex: 'isSecondClaim',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'isSecondClaim' && this.props.sortedOrder,
                render: text => conventEnumValueToString(isYorN, text ? 1 : 2)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.isInsideShare',
                    defaultMessage: '是否生成内部分摊'
                }),
                dataIndex: 'isInsideShare',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'isInsideShare' && this.props.sortedOrder,
                render: text => conventEnumValueToString(isYorN, text ? 1 : 2)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.update,
                            children: (
                                <Link key="update" to={routes.update.format(r.id)}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                        }, {
                            id: PERMISSION.start,
                            children: (ref =>
                                <WrappedPopconfirm
                                    key="start"
                                    placement="topLeft"
                                    onConfirm={this.onClickStartBtn}
                                    id={r.id}
                                    onVisibleChange={ref.setMenuVisible}
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.validate.start',
                                        defaultMessage: '是否确认启用？'
                                    })}>
                                    <a>{
                                        this.props.intl.formatMessage({
                                            id: 'tablePanel.start',
                                            defaultMessage: '启用'
                                        })
                                    }</a>
                                </WrappedPopconfirm>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.start) && hasPermissions(r.options, PERMISSION.start)),
                        }, {
                            id: PERMISSION.stop,
                            children: (ref =>
                                <WrappedPopconfirm
                                    key="stop"
                                    placement="topLeft"
                                    onConfirm={this.onClickStopBtn}
                                    id={r.id}
                                    onVisibleChange={ref.setMenuVisible}
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.validate.stop',
                                        defaultMessage: '是否确认停用？'
                                    })}>
                                    <a>{
                                        this.props.intl.formatMessage({
                                            id: 'tablePanel.stop',
                                            defaultMessage: '停用'
                                        })
                                    }</a>
                                </WrappedPopconfirm>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.stop) && hasPermissions(r.options, PERMISSION.stop)),
                        }
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    locale={locale}
                    {...TABLE} />
            </div>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
